import * as step from '@ali/flow-step-toolkit'
import process from "process";
import * as os from "os";
import * as path from "path";
import * as fs from "fs";

const FLOW_JOB_TOKEN: string = 'FLOW_JOB_TOKEN'

export function generateLineAndNetrc(machine: string, username: string, password: string, platform: string) {
    // linux / darwin by default
    let line = `machine ${machine} login ${username} password ${password}\n`;
    let netrc = path.resolve(os.homedir(), ".netrc");

    if (step.platform.PLATFORM_WIN === platform) {
        line = `machine ${machine}\nlogin ${username}\npassword ${password}\n`;
        netrc = path.resolve(os.homedir(), "_netrc");
    }
    return {line, netrc};
}

export async function setup() {
    step.info(`Going to execute setup netrc codeup step`)

    const flowJobToken: string | undefined =
        process.env[FLOW_JOB_TOKEN]

    if (flowJobToken == undefined) {
        throw new Error('missing FLOW_JOB_TOKEN')
    }

    const serviceConnectionId = process.env["SERVICE_CONNECTION_ID"];
    if (serviceConnectionId == undefined) {
        throw new Error('missing SERVICE_CONNECTION_ID')
    }

    const codeupCertificate = await step.certificate.getCodeupCertificate(flowJobToken, serviceConnectionId as string);
    if (codeupCertificate == undefined || codeupCertificate.host == undefined || codeupCertificate.username == undefined || codeupCertificate.password == undefined) {
        throw new Error(`get codeupCertificate but error: ${JSON.stringify(codeupCertificate)}`)
    }

    const machine = codeupCertificate.host;
    const username = codeupCertificate.username;
    const password = codeupCertificate.password;
    let {line, netrc} = generateLineAndNetrc(machine, username, password, step.platform.getPlatform());

    step.info(`write machine ${machine} login ${username} password **** to netrc file: ${netrc}`)
    fs.writeFileSync(netrc, line, {flag: "a", mode: 0o600});
}